import { ForbiddenException, Injectable } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import { JwtService } from '@nestjs/jwt';
import { Web3Service } from 'src/web3/web3.service';
import { userDto } from '../user/dto/user.dto';
@Injectable()
export class AuthService {
    constructor(private readonly userService: UserService,
        private jwt: JwtService, private web3: Web3Service) {}

    async signin(username: string, password: string) {
        const user = await this.userService.findOne(username);
        if (!user) {
            throw new ForbiddenException('用户不存在，请注册');
        }
        // 用户密码进行比对
        const isPasswordValid = user.password === password;
        if (!isPasswordValid) {
            throw new ForbiddenException('用户名或者密码错误');
        }
        const token = await this.jwt.signAsync({
            username: user.name,
            sub: user.id,
        });
        return { token, userId: user.id, name: user.name, address: user.address }
    }


    async signup(userDto: userDto) {
        const user = await this.userService.findOne(userDto.name);
        if (user) {
            throw new ForbiddenException('用户已存在，请更换名称');
        }
        //不管传入参数是什么，一律设置为2，只有超级管理员可以提升普通用户-》管理员
        userDto.range=2;
        const newAdd=await this.web3.createUser(userDto);
        const res=await this.userService.addUser(userDto,newAdd);
        return res;
    }
    
}
